package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
public class DishContriller {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("根据Id查询菜品")
    public Result <List<Dish>> list(Long categoryId){
        log.info("[根据Id查询菜品]categoryId:{}",categoryId);
        List<Dish> list = dishService.list(categoryId);
        return Result.success(list);
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        dishService.updateDish(dishDTO);

        String key = "dish:"+dishDTO.getCategoryId();
        clearRedisById(key);
        return Result.success();
    }

    private void clearRedisById(String key) {
        Set keys = redisTemplate.keys(key);
        redisTemplate.delete(keys);

    }

    @GetMapping("/{id}")
    @ApiOperation("查询菜品")
    public Result<DishVO> getDishById(@PathVariable Long id){
        DishVO dishVO = dishService.getDishById(id);
        return Result.success(dishVO);
    }

    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result deleteDishByids(@RequestParam List<Long> ids){
        log.info("[删除菜品]ids:{}",ids);
        dishService.deleteDishByids(ids);

        clearRedisById("dish:*");
        return Result.success();
    }

    @GetMapping("/page")
    @ApiOperation("菜品分页")
    public Result<PageResult> findDishPage(DishPageQueryDTO dishPageQueryDTO){
        log.info("[分页获取菜品列表]dishPageQueryDTO:{}",dishPageQueryDTO);
        PageResult pageResult = dishService.findDishPage(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO){
        log.info("[新增菜品]DishDTO:{}",dishDTO);
        dishService.addDish(dishDTO);

        String key = "dish:"+dishDTO.getCategoryId();
        clearRedisById(key);
        return Result.success();
    }


}
